package com.xiaoshuidi.cloud.module.iot.uitils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * <br>
 *
 * @author Porter
 * create by 2019/8/21
 * @Emial Porter.Wang@ixiaoshuidi.com
 */
public class XiMnegStringUtils {

    public static String encryptSign(String sId, String secret, String nonce, Long timestamp) {
        StringBuilder md5 = new StringBuilder();
        md5.append(sId).append(timestamp).append(nonce).append(secret);
        String sign = MD5Util.MD5Encode(md5.toString());
        return sign;
    }

    /**
     * 将经过AES加密及Base64编码后的密文字符串解密为加密前的明文。
     * @param base64Str：加密后的密文
     * @param password：AES密钥为对接方在我司申请的sid
     * @return 返回解密后的明文
     */
    public static String decryption(String base64Str, String password) {
        try {
            //Base64 解码
            byte[] content = Base64.getDecoder().decode(base64Str);
            //指定生成随机数算法名称
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes("utf-8"));
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            SecretKeySpec key = new SecretKeySpec(secretKey.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            return new String(cipher.doFinal(content), "utf-8");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没找到算法，"+e.getMessage());
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException("没找到填充，"+e.getMessage());
        } catch (InvalidKeyException e) {
            throw new RuntimeException("无效密钥，"+e.getMessage());
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException("块大小无效，"+e.getMessage());
        } catch (BadPaddingException e) {
            throw new RuntimeException("填充损坏，"+e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("不支持的字符编码，"+e.getMessage());
        }
    }
}
